package edu.ntnu.superrss.utils.feedgrabber;

import edu.ntnu.superrss.utils.HibernateUtil;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.quartz.Job;
import org.quartz.JobExecutionContext;

/**
 *
 * @author Sigurd Fosseng <sigurd at fosseng.net>
 */
public class UrlUpdater implements Job {

    /**
     * Gets SyndFeeds from the database that has not been updated the last
     * 15 minutes and adds them to the queue.
     * @param ctx
     */
    public void execute(JobExecutionContext ctx) {
        //Dette gjøres bare her, og er greit at hibernatekoden ligger her IMO -Sigurd
        UrlQueue queue = UrlQueue.getInstance();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();

            Date for15 = new Date(new Date().getTime() - (15 * 60 * 1000)); //for 15 minutter siden fra nå
            Iterator it = session.createQuery("Select url From SyndFeedImpl where lastUpdate < ?").setParameter(0, for15).iterate();

            session.flush();
            tx.commit();

            //legger feed url i køa
            while (it.hasNext()) {
                String feed = (String) it.next();
                queue.add(new URL(feed));
            }
        } catch (MalformedURLException ex) {
            Logger.getLogger(UrlUpdater.class.getName()).log(Level.SEVERE, null, ex);
        } catch (RuntimeException e) {
            tx.rollback();
            Logger.getLogger(UrlUpdater.class.getName()).log(Level.SEVERE, null, e);
        } finally {
            session.close();
        }
    }
}
